package lab1.nio;

import config.Config;
import operations.FileOperations;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileNIO {

    public static final int TESTS_NUMBER = 1000;
    public static final String RES_FILE = "FileNIO.bin";
    public static final int BUFFER_SIZE = 4096;

    /**
     * Copy file on the local computer.
     * Method calculate time of copying using NIO.
     *
     * @param args
     */
    public static void main(String[] args) {
        for (int k = 0; k < TESTS_NUMBER; k++) {

            try {
                File f = new File(RES_FILE);
                FileOperations.getEmptyFile(f);

                try (
                    FileOutputStream fos = new FileOutputStream(f);
                    FileInputStream fis = new FileInputStream(Config.INITIAL_FILE);
                    FileChannel fosChannel = fos.getChannel();
                    FileChannel fisChannel = fis.getChannel();
                ) {
                    ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
                    long start = System.currentTimeMillis();
                    while (fisChannel.read(buffer) > 0) {
                        fosChannel.write(buffer);
                        buffer.clear();
                    }
                    long end = System.currentTimeMillis();
                    System.out.println(end - start);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
            }
        }
    }
}
